package scatter.wxminiapp.rest.basic.config;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import cn.binarywang.wx.miniapp.message.WxMaMessageRouter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by yangwei
 * Created at 2021/11/22 19:57
 */

public class WxMaConfiguration {

    @Autowired
    private WxMaProperties properties;

    @Autowired(required = false)
    private List<IMaHandlerConfigure> maHandlerConfigures;

    @ConditionalOnMissingBean
    @Bean
    public WxMaService wxMaService() {
        final List<WxMaProperties.MaConfig> configs = this.properties.getConfigs();
        if (configs == null) {
            throw new RuntimeException("请配置小程序相关配置");
        }
        WxMaService service = new CustomWxMaServiceImpl(properties);

        service.setMultiConfigs(configs
                .stream().map(a -> {
                    WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
                    config.setAppid(a.getAppId());
                    config.setSecret(a.getSecret());
                    config.setToken(a.getToken());
                    config.setAesKey(a.getAesKey());
                    return config;
                }).collect(Collectors.toMap(WxMaDefaultConfigImpl::getAppid, a -> a, (o, n) -> o)));
        return service;
    }

    @ConditionalOnMissingBean
    @Bean
    public WxMaMessageRouter wxMaMessageRouter(WxMaService wxMaService) {
        final WxMaMessageRouter newRouter = new WxMaMessageRouter(wxMaService);
        if (maHandlerConfigures != null) {
            for (IMaHandlerConfigure mpHandlerConfigure : maHandlerConfigures) {
                mpHandlerConfigure.configure(newRouter);
            }
        }
        return newRouter;
    }

}
